package cloud.keveri.chat4j.core.factory;

import cloud.keveri.chat4j.api.ChatBlender;
import cloud.keveri.chat4j.provider.BaseProviderFactory;
import cloud.keveri.chat4j.provider.SupplierType;

import java.util.HashMap;
import java.util.Map;

/**
 * Chat Factory
 * <p>
 * 作者：沈自在
 **/
public abstract class ChatFactory {

    /**
     * 厂商 Map
     */
    private static final Map<SupplierType, ChatBlender> suppliers = new HashMap<>();

    private ChatFactory() {
    }

    /**
     * 获取
     */
    public static ChatBlender acquireChatBlender(SupplierType supplierType) {
        // 1. 缓存
        if (suppliers.containsKey(supplierType)) {
            return suppliers.get(supplierType);
        }
        // 2. 创建
        ChatBlender chatBlender = createChatBlender(supplierType);
        // 3. 更新
        suppliers.put(supplierType, chatBlender);
        return chatBlender;
    }

    /**
     * 刷新
     */
    public static void refreshBlender(SupplierType supplierType) {
        refresh(supplierType);
    }

    @SuppressWarnings("all")
    private static ChatBlender createChatBlender(SupplierType supplierType) {
        BaseProviderFactory providerFactory = supplierType.getProviderFactory();
        return providerFactory.createBlender(providerFactory.acquireConfig());
    }

    @SuppressWarnings("all")
    private static void refresh(SupplierType supplierType) {
        BaseProviderFactory providerFactory = supplierType.getProviderFactory();
        providerFactory.refresh(providerFactory.acquireConfig());
        suppliers.put(supplierType, acquireChatBlender(supplierType));
    }

    /**
     * 全部刷新
     */
    public static void refresh() {
        for (SupplierType type : SupplierType.values()) {
            refresh(type);
        }
    }
}
